package com.leetcode.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Leetcode18 {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        int len = nums.length;
        if (len < 4) {
            return ans;
        }
        Arrays.sort(nums);
        for (int i = 0; i < len - 3; i++) {
            if (i > 0 && nums[i] == nums[i-1]) {
                continue;
            }

            if (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) {
                break;
            }

            if (nums[i] + nums[len - 3] + nums[len - 2] + nums[len - 1] < target) {
                continue;
            }

            for (int j = i+1; j < len - 2; j++) {
                if (j > i+ 1 && nums[j] == nums[j-1]) {
                    continue;
                }

                if (nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) {
                    break;
                }

                if (nums[i] + nums[j] + nums[len - 2] + nums[len - 1] < target) {
                    continue;
                }
                int left = j + 1, right = len - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
//                        List<Integer> lst = new ArrayList<>();
//                        lst.add(nums[i]);
//                        lst.add(nums[j]);
//                        lst.add(nums[left]);
//                        lst.add(nums[right]);
//                        ans.add(lst);
                        ans.add(new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[left], nums[right])));
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        left++;
                        while (left < right && nums[right] == nums[right -1]) {
                            right--;
                        }
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        right--;
                    }

                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] nums = {1, 0, -1, 0, -2, 2};
        new Leetcode18().fourSum(nums, 0);
    }

}
